package com.ufaud.ais.sys.webapp.action;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ufaud.ais.pub.webapp.action.BaseAction;
import com.ufaud.ais.sys.entity.MenuItem;
import com.ufaud.ais.sys.service.IMenuItemService;

public class MenuAction extends BaseAction {

	private static Log LOG = LogFactory.getLog(MenuAction.class);

	private Long id;
	private MenuItem menuItem;
	private List<MenuItem> menuItemList;

	private IMenuItemService menuItemService;

	// public String list() {
	// menuItemList = menuItemService.getAll();
	// return SUCCESS;
	// }

	public String edit() {
		LOG.debug("id=" + id);
		menuItem = menuItemService.getMenuItemWithSuperMenuItem(id);
		menuItemList = menuItemService.getAncestorAndSiblingMenuItemById(id);
		return SUCCESS;
	}

	public String create() {
		menuItemList = menuItemService.getAll();
		System.out.println(menuItemList);
		return SUCCESS;
	}

	public String view() {
		LOG.debug("id=" + id);
		menuItem = menuItemService.get(id);
		return SUCCESS;
	}

	public String doInsert() {
		if (menuItem.getSuperMenuItem().getMenuItemId().equals(-1L)) {
			menuItem.setSuperMenuItem(null);
		}
		try {
			menuItemService.save(menuItem);
			Long newId = menuItem.getMenuItemId();
			LOG.debug("menuItem inserted, id=" + newId);
			addJsonObjectProperty("success", "success");
			addJsonObjectProperty("id", newId + "");
		} catch (Exception e) {
			LOG.error(e);
			addJsonObjectProperty("exception", e.getMessage());
		}
		return SUCCESS;
	}

	public String doUpdate() {
		if (menuItem.getSuperMenuItem().getMenuItemId().equals(-1L)) {
			menuItem.setSuperMenuItem(null);
		}
		try {
			menuItemService.updateMenuItem(menuItem);
			addJsonObjectProperty("id", menuItem.getMenuItemId() + "");
			addJsonObjectProperty("success", "success");
		} catch (Exception e) {
			LOG.error(e);
			addJsonObjectProperty("exception", e.getMessage());
		}
		return SUCCESS;
	}

	public String doDelete() {
		LOG.debug("id=" + id);
		try {
			menuItemService.deleteMenuItemById(id);
			addJsonObjectProperty("success", "success");
		} catch (Exception e) {
			LOG.error(e);
			addJsonObjectProperty("exception", e.getMessage());
		}
		return SUCCESS;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public MenuItem getMenuItem() {
		return menuItem;
	}

	public void setMenuItem(MenuItem menuItem) {
		this.menuItem = menuItem;
	}

	public List<MenuItem> getMenuItemList() {
		return menuItemList;
	}

	public void setMenuItemList(List<MenuItem> menuItemList) {
		this.menuItemList = menuItemList;
	}

	public void setMenuItemService(IMenuItemService menuItemService) {
		this.menuItemService = menuItemService;
	}

}
